package com.cmhi.base.utils;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;

import androidx.annotation.NonNull;

import com.cmhi.base.provider.BimDataManager;
import com.softmbh.kellyplatform.util.AppUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Arrays;

public class BimTools {

    private static Context mContext;

    private BimTools() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    public static void init(Context context) {
        mContext = context.getApplicationContext();
        BimDataManager.init(mContext);
        ToastUtils.init(mContext);
    }

    public static Context getAppContext() {
        return mContext;
    }


    /**
     * @return 执行命令后返回结果
     */
    public static String execCmd(String[] args) {
        AppUtils.debugLog("execCmd : " + Arrays.toString(args));
        String result = "";
        ProcessBuilder processBuilder = new ProcessBuilder(args);
        Process process = null;
        InputStream errIs = null;
        InputStream inIs = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read;
            process = processBuilder.start();
            errIs = process.getErrorStream();
            while ((read = errIs.read()) != -1) {
                baos.write(read);
            }
            baos.write('\n');
            inIs = process.getInputStream();
            while ((read = inIs.read()) != -1) {
                baos.write(read);
            }
            byte[] data = baos.toByteArray();
            result = new String(data);
        } catch (Exception e) {
            AppUtils.debugLog("execCmd " + Arrays.toString(args) + " error : " + e);
            e.printStackTrace();
        } finally {
            try {
                if (errIs != null) {
                    errIs.close();
                }
                if (inIs != null) {
                    inIs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        AppUtils.debugLog("execCmd " + Arrays.toString(args) + " result : " + result);
        return result;
    }

    //执行命令
    public static void execCmd(String cmd) {
        try {
            AppUtils.debugLog("exec start, cmd : " + cmd);
            Runtime.getRuntime().exec(cmd);
            AppUtils.debugLog("exec finish");
        } catch (Exception e) {
            AppUtils.debugLog("exec error");
            e.printStackTrace();
        }
    }

    public static long getAvailRAMMem() {
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi.availMem;
    }

    public static long getTotalRAMMem() {
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi.totalMem;
    }

    /*显示RAM的可用和总容量，RAM相当于电脑的内存条*/
    @NonNull
    public static String showRAMInfo() {
        return bytes2kb(getAvailRAMMem()) + "/" + bytes2kb(getTotalRAMMem());
    }

    public static long getAvailROMMem() {
        File file = Environment.getDataDirectory();
        StatFs statFs = new StatFs(file.getPath());
        long blockSize = statFs.getBlockSize();
        long availableBlocks = statFs.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    public static long getTotalROMMem() {
        File file = Environment.getDataDirectory();
        StatFs statFs = new StatFs(file.getPath());
        long blockSize = statFs.getBlockSize();
        long totalBlocks = statFs.getBlockCount();
        return totalBlocks * blockSize;
    }

    /*显示RAM的可用和总容量，RAM相当于电脑的内存条*/
    public static String showROMInfo() {
        return bytes2kb(getAvailROMMem()) + "/" + bytes2kb(getTotalROMMem());
    }

    //定义GB的计算常量
    private static final int GB = 1024 * 1024 * 1024;
    //定义MB的计算常量
    private static final int MB = 1024 * 1024;
    //定义KB的计算常量
    private static final int KB = 1024;

    public static String bytes2kb(long bytes) {
        //格式化小数
        DecimalFormat format = new DecimalFormat("###.0");
        if (bytes / GB >= 1) {
            return format.format(bytes / GB) + "GB";
        } else if (bytes / MB >= 1) {
            return format.format(bytes / MB) + "MB";
        } else if (bytes / KB >= 1) {
            return format.format(bytes / KB) + "KB";
        } else {
            return bytes + "B";
        }
    }

    @NonNull
    public static String bytes2mb(long bytes) {
        //格式化小数
        DecimalFormat format = new DecimalFormat("###.0");
        return format.format(bytes / MB) + "MB";
    }

    public static int getVersionCode(String packageName) {
        try {
            PackageInfo packageInfo = mContext.getPackageManager().getPackageInfo(packageName, 0);
            if (packageInfo != null) {
                return packageInfo.versionCode;
            }
            return 0;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }


    //静默卸载
    public static void silenceUninstall(String packageName) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            execCmd("pm uninstall " + packageName);
        } else {


            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            PackageInstaller packageInstaller = mContext.getPackageManager().getPackageInstaller();
            packageInstaller.uninstall(packageName, pendingIntent.getIntentSender());
        }
    }

    //小米开机自启
    public static void xiaomiAutoBoot(String packageName) {
        AppUtils.debugLog("start xiaomiAutoBoot arg : " + packageName);
        try {
            Bundle extras = new Bundle();
            extras.putString("start_3rd_app", packageName);//第二个参数传自己包名是设置开机自启，传 "aaa" 是取消开机自启
            mContext.getContentResolver().call(Uri.parse("content://com.mitv.security.permission"),
                    "start3rdApp", packageName, extras);
        } catch (Exception e) {
            AppUtils.debugLog("fail to call method start3rdApp : " + e);
            e.printStackTrace();
        }
    }
}
